package com.ecosoft.config;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ecosoft.config.spi.IConfigContext;

class ConfigContext implements IConfigContext {
	private static final Logger LOG = LoggerFactory.getLogger(ConfigContext.class);
	private File commonDir = null;
	private Map<String, String> attributes = new HashMap<String, String>();
    public void setContextAttributes(Map<String, String> attributes)
    {
    	this.attributes = attributes;
    }
	public ConfigContext(String configdir) {
		File lconfigdir = new File(configdir);
		if (lconfigdir.exists() && lconfigdir.isDirectory()) {
			commonDir = lconfigdir;
		}else
		{
			LOG.error("The config directory "+ configdir + "is invalid.");
		}
	}

	public File getCommonDir() {
		return commonDir;
	}

	public File getFileInCommonDir(String fileName) {
		if (commonDir == null) {
			return null;
		} else {
			File[] files = commonDir.listFiles(new FileNameFilter("^"
					+ fileName + "$"));
			if (files != null && files.length > 0) {
				return files[0];
			}
		}
		return null;
	}

	public File[] getFileInCommonDirByRegex(String regex) {
		if (commonDir == null) {
			return null;
		} else {
			return commonDir.listFiles(new FileNameFilter(regex));
		}
	}

	public File[] getFilesInCommonDir(String endswith) {
		if (commonDir == null) {
			return null;
		} else {
			return commonDir.listFiles(new FileNameFilter("*" + endswith + "&"));
		}
	}

	class FileNameFilter implements java.io.FilenameFilter {
		private String regex;

		public FileNameFilter(String cregex) {
			regex = cregex;
		}

		public boolean accept(File dir, String name) {
			Pattern pattern = Pattern.compile(regex);
			Matcher matcher = pattern.matcher(name);
			return matcher.find();
		}
	}

	public String getContextAttribute(String key) {
		return attributes.get(key);
	}

	public void setContextAttribute(String key, String value) {
		attributes.put(key, value);
	}
}
